package com.yueman.ptoolopenticket.ticket.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.json.JSONUtil;
import com.yueman.ptoolopenticket.ticket.TicketService.CommonService;
import com.yueman.ptoolopenticket.ticket.dto.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
@Slf4j
@RequestMapping(value = "/ticket")
public class CommonTicketController {
    @Autowired
    Map<String, CommonService> map;

    @RequestMapping(value = "jump")
    public Result jump(HttpServletRequest request) {
        Map<String, String> Strmap = JSONUtil.toBean(ServletUtil.getBody(request), Map.class);
        String action = Strmap.get("action");
        Map<String, Object> retMap = getJumpMethod(action);
        if (retMap.size() == 0) {
            return null;
        }
        Method mt = (Method) retMap.get("method");
        Object targetClass = retMap.get("class");
        Class<?>[] parameterTypes = mt.getParameterTypes();
        if (parameterTypes.length > 0) {
            Result result = ReflectUtil.invoke(targetClass, mt, BeanUtil.mapToBean(Strmap, parameterTypes[0], false, CopyOptions.create().setFieldMapping(Strmap)));
            return result;
        } else {
            Class<?> returnType = mt.getReturnType();
            if (String.class.isAssignableFrom(returnType)) {
                return ReflectUtil.invoke(targetClass, mt);
            } else {
                return ReflectUtil.invoke(targetClass, mt);
            }
        }
    }

    private Map<String, Object> getJumpMethod(String action) {
        HashMap<String, Object> resData = new HashMap<>();
        for (Map.Entry<String, CommonService> entry : map.entrySet()) {
            for (Method declaredMethod : entry.getValue().getClass().getDeclaredMethods()) {
                if (declaredMethod.getName().equals(action)) {
                    log.info("方法名：{}", declaredMethod.getName());
                    log.info("值：{}", entry.getValue());
                    resData.put("method", declaredMethod);
                    resData.put("class", entry.getValue());
                    return resData;
                }
            }
        }
        return resData;
    }

}
